package cn.lsc.exception;

import cn.lsc.enums.GlobalEnums;
import cn.lsc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Component
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public JSONResult globalException(Exception e){
        e.printStackTrace();
        log.info("捕获全局异常！");
        return JSONResult.error(GlobalEnums.ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult globalCustomException(GlobalCustomException e){
        e.printStackTrace();
        log.info("捕获自定义异常！");
        return JSONResult.error(e);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult globalMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sbr = new StringBuilder();
        //将303在domain里写的注解里面的错误信息全部取出来
        e.getBindingResult().getAllErrors().forEach(item->{
            sbr.append(item.getDefaultMessage()).append(";");
        });
        log.info("捕获全局异常！"+sbr.toString());
        return JSONResult.error(sbr.toString());
    }

}
